import axios from 'axios'
import type {
  InternalAxiosRequestConfig,
  AxiosInstance,
  AxiosResponse
} from 'axios'

import useUserStore from '@/stores/modules/user'
import router from '@/router/index'

// 1.单独使用 message 消息提示
import { createDiscreteApi } from 'naive-ui'
import { userReflesh } from '@/api/user'

let userStore: any = null
const { message } = createDiscreteApi(['message'])

const service: AxiosInstance = axios.create({
  baseURL: 'http://127.0.0.1:3000/api/v1',
  timeout: 5000,
  maxContentLength: Infinity,
  maxBodyLength: Infinity
})

// 接口重发的队列
interface PendingTask {
  config: InternalAxiosRequestConfig
  resolve: Function
}
let refreshing = false
let queue: PendingTask[] = []

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 配置token字段
    if (!userStore) {
      userStore = useUserStore()
    }
    const myToken = userStore.token
    if (myToken) {
      config.headers.Authorization = 'Bearer ' + myToken.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 进行响应拦截
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // console.log('222')

    // 说明出现了业务异常
    if (response.data.code && response.data.code !== 0) {
      const { config } = response
      // 看是否正在进行token刷新，加入队列
      if (refreshing && !config.url?.includes('/reflesh')) {
        return new Promise((resolve) => {
          queue.push({
            config,
            resolve
          })
        })
      }

      // token失效处理
      if (response.data.code === 110007) {
        // 根据情况判断，进行token的刷新
        if (!config.url?.includes('/reflesh')) {
          // 说明是其他接口的请求.进行token的刷新
          refreshing = true
          userReflesh()
            .then((res) => {
              if (res.code === 0) {
                userStore.setToken(res.data)
                // 之前请求
                queue.forEach(({ config, resolve }) => {
                  resolve(service(config))
                })
                // 本请求的重发
                queue = []
                return service(config)
              }
            })
            .catch(() => {
              userStore.removeToken()
              message.warning('登录token失效了')
              router.push({
                name: 'login'
              })
              return Promise.reject('登录token失效了')
            })
            .finally(() => {
              refreshing = false
            })
        }
      }

      if (response.data.code !== 110007) {
        console.log(response.data)

        message.error(
          response.data.message.length > 20
            ? '系统异常，稍后再试'
            : response.data.message
        )
      }

      return Promise.reject(new Error(response.data.message))
    }
    return response.data
  },
  (error) => {
    console.dir(error)
    // console.log('111')

    // 出现了系统异常
    console.log(error)
    // 后端服务器关闭处理情况
    if (!error.response) {
      message.error('网络繁忙')
      return Promise.reject('网络繁忙，请稍后重试')
    }
    message.error(error.response.data.message || '系统异常')
    return Promise.reject(error)
  }
)

export default service
